<?php
class course
{
	// database
	protected $db;

	// course wrapper
	protected $wr;

	public function __construct()
	{
		$this->db=Zend_Registry::get('database');

		$this->wr=new wrapper('CId|Name|EnglishName|ClassHour|TimePlace|'.
				'Intro|Teacher|Book|Reference|Exam',
			array('CId'=>'/[0-9]+/', 'Name'=>'/.{4,}/'), 'CId');
	}

	// 出错字段
	public function err_field()
	{
		return $this->wr->field;
	}

	function check($d)
	{ 
		return $this->wr->check($d); 
	}

	// 插入一条, 返回成功的id或者－1表失败
	function add($param)
	{
		$field=$this->wr->field_string($param);
		$key=$this->wr->field_string($param, '', ':');
		$value=$this->wr->filter($param);
		$result=$this->db->query("insert into course ($field) 
				values($key)", $value);
		
		if ($result->rowCount()!=1)
			return -1;
		
		$cid=$this->db->lastInsertId();

		return $cid;
	}

	// 字符串to作者数组，格式：array(AId => 'Name', ...)
	// $s 必须以、或;号分隔。$s中所有格式为：Name(id=n)的名字将会被
	// 提取出来成为数组中 AId=>'Name'，元素，然后数组将被重新整理，
	// 去掉所有(id=n)，形成可输出的字符串。
	static function str_to_teacher(&$s)
	{
		$name=split('(、|，|;|,)', $s);
		$a=array();
		$s='';
		$sep='';
		foreach ($name as $d) {
			if (strlen($d)<1)
				continue;
			preg_match('/(.+)\(id=([0-9]+)\)$/', $d, $tmp);
			if (count($tmp)==3) { // 含有id项
				$s.=$sep.$d;
				$id=$tmp[2];
				$a[$id]=$tmp[1];
			}
			else
				$s.=$sep.$d;
			$sep=';';
		}
		return $a;
	}

	// 取全部课程简介
	function all()
	{
		$result = $this->db->query('select CId, Name, EnglishName, Intro '.
				'from course order by CId desc');
		return $result->fetchAll(Zend_Db::FETCH_ASSOC);
	}

	// 取一门课程的全部信息
	function fetch($cid)
	{
		$result = $this->db->query('select * from course where CId=:cid',
				array('cid'=>$cid));
		$rows = $result->fetchAll(Zend_Db::FETCH_ASSOC);

		if (count($rows)>0) return $rows[0];
		return array('CId'=>0,
					 'Name'=>'',
					 'EnglishName'=>'',
					 'Intro'=>'',
					 'ClassHour'=>'',
					 'TimePlace'=>'',
					 'Teacher'=>'',
					 'Book'=>'',
					 'Reference'=>'',
					 'Exam'=>'');
	}

	// 更新课程信息
	function update($param)
	{
		$value=$this->wr->filter($param);
		$result=$this->db->query('update course
			set Name=:Name, EnglishName=:EnglishName,
				Intro=:Intro, ClassHour=:ClassHour,
				TimePlace=:TimePlace, Teacher=:Teacher,
				Book=:Book, Reference=:Reference, Exam=:Exam
			where CId=:CId', $value);
		
		if ($result->rowCount()!=1)
			return false;
		return true;		
	}

	// 删除一门课程
	function del($cid)
	{
		try {
			$this->del_courseware(0, $cid);
			$this->db->query('delete from Homework where CId='.$cid);
			$this->db->query('delete from course where CId='.$cid);
			return 1;
		}
		catch (Zend_Excetpion $e) {
			return 0;
		}
	}

	// 删除课件
	function del_courseware($wid, $cid)
	{
		$dir = $_SERVER['DOCUMENT_ROOT'].'/pub/courseware';

		try {
			if (empty($wid)) { // delete a group of courseware
				system("rm -rf $dir/$cid.*");
				$this->db->query('delete from courseware where CId='.$cid);
			}
			else {
				$result=$this->db->query('select File from courseware '.
					'where WId=:wid', array('wid'=>$wid));
				$rows=$result->fetchAll(Zend_Db::FETCH_ASSOC);
				$file=$rows[0]['File'];
				if (!empty($file) && $file!='NULL') {
					// remove old icon
					unlink("$dir/$file");
				}
				$this->db->query('delete from courseware where WId='.$wid);
			}

			return 1;
		}
		catch (Zend_Exception $e) {
			return 0;
		} // end of try

	}
	
	// 删除作业
	function del_homework($hid)
	{
		$this->db->query('delete from Homework where HId='.$hid);
		return 1;
	}

	// 课件信息,如果wid==0,则取cid的所有课件，否则只取wid一个课件
	// 如果cid和wid都为0，取全部课件。
	function courseware($wid, $cid)
	{
		$wid=intval($wid);
		$cid=intval($cid);
		$where = '';
		if ($wid>0)
			$where = " where WId=$wid ";
		else if ($cid>0)
			$where = " where CId=$cid ";
		$result=$this->db->query('select * from courseware '.$where.
								 ' order by WId desc');
		return $result->fetchAll(Zend_Db::FETCH_ASSOC);
	}

	// 作业信息,如果$hid==0,则取$cid的所有作业，否则只取hid一个作业
	function homework($hid, $cid)
	{
		$hid=intval($hid);
		$cid=intval($cid);
		$where = empty($hid) ? " CId=$cid " : " HId=$hid ";
		$result=$this->db->query('select * from Homework where '.$where);
		return $result->fetchAll(Zend_Db::FETCH_ASSOC);
	}

	// 格式化课程信息
	static function format($data)
	{
		foreach ($data as $k => $v) {

			switch ($k) {
			case 'Description':
			case 'Intro':
			case 'TimePlace':
			case 'Reference':
				$v=strtr($v, array("\n"=>'<br />',"\r"=>'',' '=>'&nbsp;'));
				$result[$k]=preg_replace('@((?:https?|mailto).*?)(&nbsp;|<br|$)@', '<img src="/pub/image/a.gif" alt="连接:" /><a href="\1" target="_blank">\1</a>\2',	$v);
				break;

			default: $result[$k]=$v;
			} // end of switch

		}
		return $result;
	}
	
	// 教师id、姓名、头像
	function teacher($data)
	{
		$t=self::str_to_teacher(&$data);
		$result=array();
		foreach ($t as $k => $v) {
			$k = intval($k);
			$dt = $this->db->query("select Name, Icon from account ".
					" where AId=$k");
			$row = $dt->fetchAll(Zend_Db::FETCH_ASSOC);
			if (count($row)<1) continue;

			$tmp = $row[0];
			$result[] = array('AId'=>$k, 'Name'=>$tmp['Name'],
				'Icon'=>empty($tmp['Icon'])?'default.gif':$tmp['Icon']);
		}
		return $result;
	}

	// 增加作业
	function add_homework($cid, $param)
	{
		$teacher = auth::name();
		$title = $param['Title'];
		if (empty($title))
			$title = 'Homework_'.time();

		try {
			$this->db->query('insert into Homework '.
					'(CId, Title, Description, Teacher, Deadline) '.
					'values (:cid, :title, :desc, :teach, :dead)',
				array('cid'=>$cid, 'title'=>$title,
					  'desc'=>$param['Description'],
					'teach'=>$teacher, 'dead'=>$param['Dead']));
			return 1;
		}
		catch (Zend_Exception $e) {
			return 0;
		} // end of try

	}
};
?>
